package com.liuhuxiang.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 新建订单服务
 * @author liuhuxiang
 * @version: OrderController.java, 2023年02月27日 下午12:13 liuhuxiang  Exp $
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    RestTemplate restTemplate;


   @RequestMapping("/add")
   public String add(){
       System.out.println("下单成功");

       //我需要在这里去调用stock的远程接口，通过RestTemplate
       //getForObject 的参数 1 远程调用地址   2 响应参数的类型   3入参的类型   本接口没有入参，只要两个参数即可
       String msg = restTemplate.getForObject("http://stock-service/stock/reduct", String.class);
       return "Hello World"+msg;
   }


    /*****************************************下面是流控降级需要用到的请求***********************************/

    @RequestMapping("/header")
    public String header(@RequestHeader("X-Request-color") String color){
        return color;
    }


    @RequestMapping("/flow")
    //@SentinelResource(value = "flow",blockHandler = "flowBlockHandler")
    public String flow() throws InterruptedException {
        return "正常访问";
    }



    @RequestMapping("/flowThread")
    //@SentinelResource(value = "flowThread",blockHandler = "flowBlockHandler")
    public String flowThread() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        System.out.println("正常访问");
        return "正常访问";
    }


    // 关联流控  访问/add 触发/get
    @RequestMapping("/get")
    public String get() throws InterruptedException {
        return "查询订单";
    }



    @RequestMapping("/err")
    public String err()  {
        int a=1/0;
        return "hello";
    }


    /**
     * 热点规则，必须使用@SentinelResource
     * @param id
     * @return
     * @throws InterruptedException
     */
    @RequestMapping("/get/{id}")
    public String getById(@PathVariable("id") Integer id) throws InterruptedException {

        System.out.println("正常访问");
        return "正常访问";
    }

}